<template>
  <div>
    <ul class="imglist">
      <li :key="index" @click="preview(index)" v-for="(src, index) in fileList">
        <img :src="src" alt="">
      </li>
    </ul>
    <el-upload ref="uploadPics" action="/api/uploadImage" accept="image/jpeg,image/gif,image/png" multiple list-type="picture-card" :before-upload="beforeUpload" :on-remove="handleRemove" :on-change="handleChange" :on-success="handleSuccess" :on-error="handleError" >
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>
<script>
export default {
  props: [ ],
  data: function () {
    return {
      imgQuality: 0.5,
      imgs: [
        {
          url: '',
          title: '',
          preview: '1'
        }
      ],
      imgList: [],
      fileList: []
    }
  },
  methods: {
    getImageIds () {
      return this.imgList
    },
    setImageList (imglist, imgids) {
      this.imgList = imgids
      this.fileList = []
      if (imglist) {
        imglist.forEach((item) => {
          this.fileList.push(item.url)
        })
      }
      this.$refs.uploadPics.clearFiles()
      // this.fileList = imgList
      // this.$previewRefresh()
    },
    preview (index) {
      this.$imagePreview({
        images: this.fileList,
        index: index
      })
    },
    dataURItoBlob (dataURI, type) {
      var binary = atob(dataURI.split(',')[1])
      var array = []
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i))
      }
      return new Blob([new Uint8Array(array)], {type: type})
    },
    beforeUpload (param) {
      // 对图片进行压缩
      const imgSize = param.size / 1024 / 1024
      if (imgSize > 1) {
        const _this = this
        return new Promise(resolve => {
          const reader = new FileReader()
          const image = new Image()
          image.onload = (imageEvent) => {
            const canvas = document.createElement('canvas')
            const context = canvas.getContext('2d')
            const width = image.width * _this.imgQuality
            const height = image.height * _this.imgQuality
            canvas.width = width
            canvas.height = height
            context.clearRect(0, 0, width, height)
            context.drawImage(image, 0, 0, width, height)
            const dataUrl = canvas.toDataURL(param.type)
            const blobData = _this.dataURItoBlob(dataUrl, param.type)
            resolve(blobData)
          }
          reader.onload = e => { image.src = e.target.result }
          reader.readAsDataURL(param)
        })
      } else {
        return new Promise(resolve => {
          const reader = new FileReader()
          const image = new Image()
          image.onload = (imageEvent) => {
            // const width = image.width
            // const height = image.height
            // _this.imgWidthHeight = `${width}/${height}`
            // console.log(`图片上传前，不需要压缩：${_this.imgWidthHeight}`)
            resolve()
          }
          reader.onload = e => { image.src = e.target.result }
          reader.readAsDataURL(param)
        })
      }
    },
    // 处理图片预览效果
    handlePreview (file) {
      this.previewPath = file.url
      this.previewVisible = true
    },
    // 处理移除图片的操作
    handleRemove (file) {
      //* 1. 获取将要删除的图片的临时路径
      console.log(file)
      const { tmpPath } = file.response
      //* 2. 从 pics 数组中，找到这个图片对应的索引值
      const i = this.form.pics.findIndex(item => item.pic === tmpPath)
      //* 3. 调用数组的splice方法，把图片信息对象，从pics数组中移除
      this.form.pics.splice(i, 1)
    },
    handleChange (file, fileList) {
      this.imgNum = fileList.length
      const el = document.getElementsByClassName('el-upload')[0]
      if (fileList.length >= this.limit - 0) {
        el.style.display = 'none'
      }
    },
    handleSuccess (res, file, fileList) {
      this.imgList.push(file.response.data.id)
      this.$notify.success({
        title: '成功',
        message: `文件上传成功`
      })
    },
    // 文件上传失败时的钩子
    handleError (err, file, fileList) {
      console.log(err)
      console.log(file)
      console.log(fileList)
      this.$notify.error({
        title: '错误',
        message: `文件上传失败`
      })
    }
  }
}
</script>
<style>
@import "../assets/css/global.css";
img {
  width: 145px;
  height: 145px;
  padding: 0 5px;
}
.imglist {
  text-align: left;
}

.imglist > li {
  display: inline;
}
</style>
